using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JumpBox : MonoBehaviour
{
    [Range(0, 10)] public float jumpVelocity = 5f;
    public LayerMask mask;
    public float boxHeight = 0.5f;

    private Vector2 _playerSize;
    private Vector2 _boxSize;

    private bool _jumpRequest = false;
    private bool _grounded = false;

    private Rigidbody2D _rigidbody2D;
    
    // Start is called before the first frame update
    void Start()
    {
        _rigidbody2D = GetComponent<Rigidbody2D>();
        _playerSize = GetComponent<SpriteRenderer>().bounds.size;
        _boxSize = new Vector2(_playerSize.x * 0.8f, boxHeight);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Jump") && _grounded)
        {
            _jumpRequest = true;
        }
    }

    private void FixedUpdate()
    {
        if (_jumpRequest)
        {
            _rigidbody2D.AddForce(Vector2.up * jumpVelocity, ForceMode2D.Impulse);

            _jumpRequest = false;
            _grounded = false;
        }
        else
        {
            Vector2 boxCenter = (Vector2) transform.position + Vector2.down * _playerSize.y * 0.5f;
            if (Physics2D.OverlapBox(boxCenter, _boxSize, 0, mask) != null)
            {
                _grounded = true;
            }
            else
            {
                _grounded = false;
            }
        }
    }

    private void OnDrawGizmos()
    {
        if (_grounded)
        {
            Gizmos.color = Color.red;
        }
        else
        {
            Gizmos.color = Color.green;
        }
        
        Vector2 boxCenter = (Vector2) transform.position + Vector2.down * _playerSize.y * 0.5f;
        Gizmos.DrawWireCube(boxCenter, _boxSize);
    }
}
